package com.xn.app.muying.activity;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.xn.app.muying.R;
import com.xn.app.muying.adpter.BuyTimeAdapter;
import com.xn.app.muying.bean.BuyTimeBean;
import com.xn.app.muying.sqlite.DBManager;
import com.xn.app.muying.util.APIMethod;
import com.xn.app.muying.util.BaseActivity;
import com.xn.app.muying.util.HttpUtil;
import com.xn.app.muying.util.MyAlertDialog;
import com.xn.app.muying.util.NetworkUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;

import okhttp3.Request;

/**
 * 胎心-购买服务页面
 * Created by Administrtor on 2016/11/23.
 */
public class BuyServiceActivity extends BaseActivity implements View.OnClickListener, HttpUtil.OnGetDataListener, AdapterView.OnItemClickListener {

    //购买次数选择
    private ListView listview;
    private Handler handler = new Handler();
    private BuyTimeAdapter buyTimeAdapter;
    //数据显示页面
    private RelativeLayout relativeLayout = null;
    private TextView textview = null;
    //无数据显示页面
    private LinearLayout no_data_linearlayout = null;
    //购买实时监测数据集合
    public static ArrayList<BuyTimeBean> list;
    //标记当前item位置
    public static int mIndex = 0;
    //加载框
    AlertDialog dialog;
    //类对象
    public static BuyServiceActivity buyServiceActivity = null;
    //数据库
    private DBManager db = null;
    //返回键
    private ImageView img_back=null;
    //标题
    private TextView title_name=null;
    Button next;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_buyservice);
        buyServiceActivity = this;
        db = new DBManager(BuyServiceActivity.this);
        listview = (ListView) findViewById(R.id.activity_buyservice_listview);
        textview = (TextView) findViewById(R.id.textview);
        next = (Button) findViewById(R.id.activity_buyservice_next);
        relativeLayout = (RelativeLayout) findViewById(R.id.relativeLayout);
        no_data_linearlayout = (LinearLayout) findViewById(R.id.no_data_linearlayout);
        title_name=(TextView) findViewById(R.id.title_name);
        img_back = (ImageView) findViewById(R.id.img_back);
        img_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        title_name.setText("服务内容");
        next.setOnClickListener(this);
        listview.setOnItemClickListener(this);
        buyTimeAdapter = new BuyTimeAdapter(BuyServiceActivity.this);
        listview.setAdapter(buyTimeAdapter);
        if (NetworkUtil.isNetworkAvailable(BuyServiceActivity.this)) {
            dialog = new MyAlertDialog().ShowDialog(BuyServiceActivity.this, R.layout.dialog_loading);
            dialog.setCancelable(true);
            getData();
        } else {
            no_data_linearlayout.setVisibility(LinearLayout.VISIBLE);
        }

    }

    @Override
    public void onClick(View view) {
        Intent intent = new Intent();
        if (mIndex != -1) {
            intent.putExtra("companyName", list.get(mIndex).getCompanyName());
            intent.putExtra("name", list.get(mIndex).getName());
            intent.putExtra("serviceType", list.get(mIndex).getServiceType());
            intent.putExtra("serviceCount", list.get(mIndex).getServiceCount());
            intent.putExtra("price", list.get(mIndex).getPrice());
            intent.putExtra("id", list.get(mIndex).getId());
            intent.putExtra("description", list.get(mIndex).getDescription());
            intent.putExtra("sign", "BuyServiceActivity");
            intent.setClass(BuyServiceActivity.this, ReadyPayActivity.class);
            startActivity(intent);
        } else {
            Toast.makeText(BuyServiceActivity.this, "请选择购买类型", Toast.LENGTH_SHORT).show();
        }
    }


    public void getData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Request request = new Request.Builder().url(APIMethod.Buy_Time(1)).addHeader("Authorization", db.select("token_type") + " " + db.select("access_token")).get().build();
                    okhttp3.Response response = MuYingApplication.mOkHttpClient.newCall(request).execute();
                    String bodys = response.body().string();
                    onJsonData(bodys);
                } catch (IOException e) {
                    e.printStackTrace();

                }
            }


        }).start();
    }

    //获取购买实时监测次数数据
    public void onJsonData(String data) {
        Log.i("lll", data + "");
        try {
            JSONObject jsonObject = new JSONObject(data);
            JSONArray items = jsonObject.getJSONArray("items");
            list = new ArrayList<>();
            for (int i = 0; i < items.length(); i++) {
                JSONObject object = items.getJSONObject(i);
                String name = object.optString("name");
                String serviceTypeId = object.optString("serviceTypeId");
                String serviceType = object.optString("serviceTypeName");
                String serviceCount = object.optString("serviceCount");
                String price = object.optString("price");
                String compnayId = object.optString("compnayId");
                String companyName = object.optString("companyName");
                String description = object.optString("description");
                String originalPrice = object.optString("originalPrice");
                String paySuccessDescription = object.optString("paySuccessDescription");
                String id = object.optString("id");
                BuyTimeBean buyTimeBean = new BuyTimeBean();
                buyTimeBean.setName(name);
                buyTimeBean.setServiceTypeId(serviceTypeId);
                buyTimeBean.setServiceType(serviceType);
                buyTimeBean.setServiceCount(serviceCount);
                buyTimeBean.setPrice(price);
                buyTimeBean.setDescription(description);
                buyTimeBean.setOriginalPrice(originalPrice);
                buyTimeBean.setPaySuccessDescription(paySuccessDescription);
                buyTimeBean.setCompnayId(compnayId);
                buyTimeBean.setCompanyName(companyName);
                buyTimeBean.setId(id);
                //开发权限
                if (!id.equals("17")) {
                    list.add(buyTimeBean);
                }
            }
            dialog.dismiss();
            buyTimeAdapter.getData(list);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Intent intent = new Intent();
                    relativeLayout.setVisibility(RelativeLayout.VISIBLE);
                    intent.putExtra("companyName", list.get(mIndex).getCompanyName());
                    intent.putExtra("name", list.get(mIndex).getName());
                    intent.putExtra("serviceType", list.get(mIndex).getServiceType());
                    intent.putExtra("serviceCount", list.get(mIndex).getServiceCount());
                    intent.putExtra("price", list.get(mIndex).getPrice());
                    intent.putExtra("id", list.get(mIndex).getId());
                    intent.putExtra("description", list.get(mIndex).getDescription());
                    intent.putExtra("sign", "BuyServiceActivity");
                    intent.setClass(BuyServiceActivity.this, ReadyPayActivity.class);
                    startActivity(intent);
                }
            });

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        mIndex = i;
        buyTimeAdapter.notifyDataSetChanged();

    }

    @Override
    protected void onResume() {
        super.onResume();
    }
}
